package com.smart.buss.ctrl;

import java.util.*;

import com.smart.buss.service.BussCodeService;
import com.smart.buss.vo.BussCode;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.smart.buss.service.BussDakaLogService;
import com.smart.buss.service.BussDakaService;
import com.smart.buss.service.BussSetService;
import com.smart.buss.vo.BussDaka;
import com.smart.buss.vo.BussDakaLog;
import com.smart.buss.vo.BussSet;
import com.smart.primary.common.common.BaseCtrl;
import com.smart.primary.common.util.AjaxResult;
import com.smart.primary.common.util.DateUtil;

@RestController
@RequestMapping("/buss/daka")
public class BussDakaController extends BaseCtrl {
	private final static Logger logger= Logger.getLogger(BussDakaController.class);

	@Autowired
	private BussDakaService bussDakaService;
	@Autowired
	private BussDakaLogService bussDakaLogService;
	@Autowired
	private BussSetService bussSetService;

	@Autowired
	private BussCodeService bussCodeService;

	@RequestMapping
	public AjaxResult getList(BussDaka entity) throws Exception{
		List<BussDaka> list=bussDakaService.queryListByPage(entity);
		return getResult(entity, list);
	}

	@RequestMapping("list")
	public List<BussDaka> list(BussDaka entity) throws Exception{
		return bussDakaService.queryList(entity);
	}

	//@Scheduled(cron = "0 0 14 * * ?")
	@Scheduled(cron = "* 0/5 * * * ?")
	@Transactional
	public void save() throws Exception{
		if(!JobRun.hasStartServer(BussDakaController.class.toString())){
			if(JobRun.putStartServer(BussDakaController.class.toString())) {
				try {
					BussDaka entity = new BussDaka();
					entity.setStatus(0);
					String issueNumber = null;
					BussDaka query = bussDakaService.queryObject(entity);
					if (query != null && new Date().after(query.getCloseTime())) {
						query.setStatus(1);
						query.setUpdateDate(new Date());
						bussDakaService.update(query);
						issueNumber = distribute(query);
					}
					createActivity(issueNumber);
				} finally {
					JobRun.delStartServer(BussDakaController.class.toString());
				}
			}
		}
	}
	
	private void createActivity(String upIssueNumber) throws Exception {
		 
		BussDaka entity=new BussDaka();
		entity.setStatus(0);
		BussDaka query=bussDakaService.queryObject(entity);
		if(query==null) {
			//查询是否有互动
			entity.setUpIssueNumber(upIssueNumber);
			entity.setQihao(DateUtil.getNowDate());
			entity.setIssueNumber(UUID.randomUUID().toString().substring(0, 10));
			entity.setJiangPrice(0);
			entity.setZongPrice(500);
			entity.setZongNum(0);
			entity.setStatus(0);//0进行中；1开奖中;2结束
			entity.setCloseTime(DateUtil.DsDay_Minute(new Date(), 10));//1天
			bussDakaService.insert(entity);
		}

	}

	private String distribute(BussDaka query) throws Exception {
		

		
		if(query ==null) {
			logger.info("进入分配奖池IssueNumber is null");
			return "";
		}
		logger.info("进入分配奖池IssueNumber:"+query.getIssueNumber());
		String dakaId = query.getIssueNumber();
		// 获取当前期数的所以记录
		BussDakaLog log=new BussDakaLog();
		log.setDakaId(dakaId);
		log.setDakaStatus(0);
		log.setType(0);
		List<BussDakaLog> logList=bussDakaLogService.queryList(log);
		if(logList==null || logList.size()==0){
			logger.info("进入分配奖池BussDakaLog is null");
			query.setStatus(2);
			query.setRemarks("流标");
			bussDakaService.update(query);
		}
		//获取设置
		BussSet set=bussSetService.queryObject(null);
		Integer zuixiao = (int)(set.getZuixiao()*100);
		Integer beilv = (int)(double)(set.getBeilv());
		Double bili = set.getBili();
		logger.info("最小保证金"+zuixiao);
		logger.info("倍率"+beilv);
		logger.info("比例"+bili);

		/**
		 *  获取打卡金总和
		 */
		int zongPrice=0;
		for (BussDakaLog dakaLog: logList) {
			zongPrice+=dakaLog.getDakaPrice();
		}
		logger.info("打卡金总和"+zongPrice);

		/**
		 * 获取奖池的金额
		 */
		Integer price=(int)(zongPrice*bili);
		Integer jiangPrice= price-(zuixiao*logList.size());
		logger.info("奖池金额"+price);
		logger.info("奖池金额扣除保障金后"+jiangPrice);

		/**
		 * 分配奖金
		 */
		int succNum = 0;
		for (BussDakaLog dakaLog: logList) {
			Integer zhidazhi=dakaLog.getDakaPrice()*beilv;
			Integer val=(int)(Math.random()*zhidazhi);
			if(jiangPrice>=val){
				dakaLog.setPaifaPrice(zuixiao+val);
				jiangPrice=jiangPrice-val; //奖池金额逐步减少
			}else if(jiangPrice.doubleValue()>0){
				dakaLog.setPaifaPrice(zuixiao+jiangPrice);
				jiangPrice=0; //奖池金额扣完
			}else {
				dakaLog.setPaifaPrice(zuixiao);
			}
		}
		// 保存日志集合
		for (BussDakaLog dakalog:logList) {
			bussDakaLogService.updateAll(dakalog);
		}

		BussDakaLog log2=new BussDakaLog();
		log2.setDakaId(dakaId);
		Integer logList2=bussDakaLogService.queryCount(log);
		//更新分奖人数
		if(query.getErrorNum()==null || query.getErrorNum()==0){
			query.setErrorNum(logList2-logList.size());
		}else {
			query.setErrorNum(query.getErrorNum()-logList.size());
		}
		query.setSuccessNum(query.getSuccessNum()+logList.size());
		query.setStatus(2);
		query.setJiangPrice(query.getJiangPrice()+price);
		query.setUpdateDate(new Date());
		bussDakaService.update(query);


		/**
		 *   打卡领东西的分配
		 */

		BussDakaLog llog=new BussDakaLog();
		llog.setDakaId(dakaId);
		llog.setDakaStatus(0);
		llog.setType(1);
		List<BussDakaLog> llogList=bussDakaLogService.queryList(llog);
		logger.info("爱奇艺打卡人数"+llogList.size());
		Integer prize = set.getPrizenum();

		BussCode bussCode=new BussCode();
		bussCode.setIsuse(0);
		bussCode.setPageSize(prize);
		List<BussCode> codeList=bussCodeService.queryListByPage(bussCode);
		logger.info("激活码的数量================"+codeList.size());
		if(llogList!=null){
			if(llogList.size()>prize){
				Set<Integer> sett=new HashSet<>();
				getIndex(sett, prize,llogList.size()); // 获取 中奖下标集合
				logger.info("中奖的下标================"+sett);

				int a=0;
				for (int i=0;i<llogList.size();i++) {
					if(sett.contains(i)){
						try {
							if(codeList!=null && codeList.size()>a+1){
								setDakaWin(llogList.get(i),codeList.get(a));
								logger.info("中奖================");
							}else {
								llogList.get(i).setDakaStatus(1);
								bussDakaLogService.update(llogList.get(i));
								logger.info("中奖=========激活码不足");
							}
						}catch (Exception e){
							logger.info("爱奇艺会员激活码不足");
						}
						a++;
					}else {
						llogList.get(i).setDakaStatus(1);
						bussDakaLogService.update(llogList.get(i));
					}
				}
			}else {  // 全部中奖
				for (int i=0;i<llogList.size();i++) {
					try {
						if(codeList!=null && codeList.size()>i+1){
							setDakaWin(llogList.get(i),codeList.get(i));
							logger.info("全部中奖================");
						}else {
							llogList.get(i).setDakaStatus(1);
							bussDakaLogService.update(llogList.get(i));
							logger.info("全部中奖=========激活码不足");
						}
					}catch (Exception e){
						logger.info("爱奇艺会员激活码不足");
					}
				}
			}
		}

		return query.getIssueNumber();
	}



	public  void getIndex(Set<Integer> set, int count,int size){
		if(count>0 && size>0){
			set.add((int)(Math.random()*size));
			if(set.size()<count){
				getIndex( set, count,size);
			}
		}
	}

	public  void setDakaWin(BussDakaLog log,BussCode bussCode) throws Exception {
		log.setDakaStatus(1);
		log.setRemarks(bussCode.getCode());
		bussDakaLogService.update(log);
		bussCode.setIsuse(1);
		bussCode.setDakaId(log.getDakaId());
		bussCode.setUserId(log.getUserId());
		bussCode.setUseDate(new Date());
		bussCodeService.update(bussCode);
	}




//	/**
//	 *  同步 打卡基金的方法
//	 */
//	@Scheduled(cron = "0 0/1 * * * ?")
//	@Transactional
//	public void aaas() throws Exception{
//		BussDakaLog entity=new BussDakaLog();
//		String benqi=DateUtil.getNowDate();
//		entity.setDakaId(benqi);
//		List<BussDakaLog> list=bussDakaLogService.queryList(entity);
//		Integer price=0;
//		for (BussDakaLog log: list) {
//			price+=log.getDakaPrice();
//		}
//		Map m=new HashMap();
//		m.put("price",price/100.0);
//		m.put("zongman",list.size());
//		m.put("benqi",benqi);
//		if(RedisUtils.getJedis()==null){
//			return;
//		}
//
//		RedisUtils.getJedis().set("dakajijin",JSON.toJSONString(m));
//	}
}
